
const {Student,Op}  = require('../sequelize/sequelize')

fn_index= async (ctx)=>{

  await Student.findAll().then(res=>{
      ctx.body=res
  })

}

fn_data= async (ctx)=>{

  let keyword = ctx.request.query.keyword

  console.log(isNaN(keyword));


  if(keyword!==''){

      if (isNaN(keyword)==false) {
          let data = await Student.findAll({
              where:{
                      [Op.or]:[
                          {id:keyword},
                          {thing1:keyword}
                      ]
              }
          })
          ctx.body=data
      }else{
          let data = await Student.findAll({
              where:{
                      [Op.or]:[
                          {title:keyword},
                          {thing2:keyword}
                      ]
              }
          })
          ctx.body=data
      }
  }else{

      await Student.findAll().then(res=>{
      ctx.body=res
      })
  }
  
}

fn_add= async (ctx)=>{

  let data = await Student.findAll().then(res=>{

      let max = 0
      for (let i in res) {
            
      if (max<res[i].id) {
              max=res[i].id
          }
      }
  
      let id = max+1
  
      let data = ctx.request.body
  
      data.id=id
  
      return data
  })

  await Student.create(data)

  await Student.findAll().then(res=>{
      ctx.body=res
  })
}



fn_edit=async (ctx)=>{
  
  let data= ctx.request.body
  
  await Student.findByPk(data.id).then(async (post)=> {
      await post.update(
          {id:data.id,
            title:data.title,
            thing1:data.thing1,
            thing2:data.thing2,
            thing3:data.thing3,
            author:data.author,
            time:data.time}
      )
  })


  await Student.findAll().then(res=>{
      ctx.body=res
  })
}

fn_Deleted=async (ctx)=>{
  
  let id = ctx.request.query.id

  await Student.destroy({
      where:{id:id}
  })

  await Student.findAll().then(res=>{
      ctx.body=res
  })

}

let get = [['/index',fn_index],['/data',fn_data],['/indexDeleted',fn_Deleted]]
let post =[['/indexadd',fn_add],['/indexedit',fn_edit]]

module.exports={
  'GET':get,
  'POST':post
}
